<template>
	<div class="box">
		<el-card class="card-css">
			<div class="zhpj">
				<span class="zhpj-span">报表打印</span>
			</div>

			<div class="table-css">
				<div class="btn-css">
					<el-button type="success" @click="machine_data"
						>冷机数据</el-button
					>
					<el-button type="success" @click="operating_data"
						>运行数据</el-button
					>
					<el-button type="success" @click="qualified"
						>能耗能效</el-button
					>
					<el-button
						type="success"
						@click="dialogVisible = !dialogVisible"
						>自定义</el-button
					>
				</div>
				<div class="select01">
					<el-select placeholder="商场">
						<el-option label="Zone one" value="shanghai" />
						<el-option label="Zone two" value="beijing" />
					</el-select>
				</div>

				<div class="select02">
					<el-select placeholder="一小时">
						<el-option label="Zone one" value="shanghai" />
						<el-option label="Zone two" value="beijing" />
					</el-select>
				</div>

				<div class="block">
					<el-date-picker
						type="daterange"
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
					/>
				</div>

				<div class="btn-01">
					<el-button type="primary" @click="exportExcel"
						>下 载</el-button
					>
				</div>
				<!-- <div class="btn-02">
					<el-button type="primary">打 印</el-button>
				</div> -->
			</div>

			<div class="table" v-if="tableStatus == 'machineData'">
				<el-table
					id="table"
					:row-key="getRowKeys"
					:data="tableData"
					style="width: 100%; height: 350px"
					:header-cell-style="{
						'text-align': 'center',
						background: '#B4C7E7',
						color: '#333333',
					}"
					:cell-style="{
						'text-align': 'center',
						background: '#f5f8fb',
					}"
				>
					<el-table-column
						v-if="midData.show[0]"
						width="150"
						label="时间"
					>
						<template #default="scope">
							<span>{{
								dayjs(scope.row.createTime).format("YY-MM-DD")
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						v-for="item in midData.refrigerator"
						:key="item.id"
						:label="item.label"
					>
						<el-table-column
							v-for="(opt, index) in item.children"
							:key="index"
							:prop="opt.prop"
							:label="opt.label"
							><template v-slot:header
								>{{ opt.label }}
							</template></el-table-column
						>

						<template v-slot:header>{{ item.label }} </template>
					</el-table-column>
				</el-table>
				<!-- <div class="pagination">
					<el-pagination
						layout="prev, pager, next, jumper"
						:total="1000"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</div> -->
			</div>

			<div class="table" v-else-if="tableStatus == 'operatingData'">
				<el-table
					:data="tableDataOperating"
					style="width: 100%"
					border
					:row-key="getRowKeys"
					:header-cell-style="{
						'text-align': 'center',
						background: '#B4C7E7',
						color: '#333333',
					}"
					:cell-style="{
						'text-align': 'center',
						background: '#f5f8fb',
					}"
				>
					<el-table-column v-if="midData.show[1]" label="时间">
						<template #default="scope">
							<span>{{
								dayjs(scope.row.createTime).format("YY-MM-DD")
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						v-for="(i, idx) in midData.runtime"
						:key="idx"
						:prop="i.prop"
						:label="i.label"
					>
						<template v-slot:header>{{ i.label }} </template>
					</el-table-column>
				</el-table>
				<!-- <div class="pagination">
					<el-pagination
						v-model:page-size="pageSize3"
						layout="prev, pager, next, jumper"
						:total="1000"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</div> -->
			</div>

			<div class="table" v-else-if="tableStatus == 'qualified'">
				<el-table
					:data="tableDataQualified"
					:row-key="getRowKeys"
					style="width: 100%"
					border
					:header-cell-style="{
						'text-align': 'center',
						background: '#B4C7E7',
						color: '#333333',
					}"
					:cell-style="{
						'text-align': 'center',
						background: '#f5f8fb',
					}"
				>
					<el-table-column v-if="midData.show[2]" label="时间">
						<template #default="scope">
							<span>{{
								dayjs(scope.row.createTime).format("YYYY-MM-DD")
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						v-for="(item, i) in midData.refrigerator"
						:key="i"
						:prop="item.prop"
						:label="item.label"
					>
						<template v-slot:header>{{ item.label }} </template>
					</el-table-column>
				</el-table>
				<!-- <div class="pagination">
					<el-pagination
						v-model:page-size="pageSize3"
						layout="prev, pager, next, jumper"
						:total="1000"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</div> -->
			</div>
		</el-card>
		<!-- 自定义弹框 -->
		<el-dialog
			v-model="dialogVisible"
			append-to-body
			title="自定义"
			ref="dialog"
			@open="open"
			width="504px"
		>
			<div class="checkbox-div">
				<div>
					<el-checkbox v-model="ckAll" label="全选" />
				</div>
				<div>冷机数据</div>
				<div>
					<el-checkbox
						v-model="ShowTime[0]"
						label="时间"
						size="large"
					/>
				</div>
				<div>
					<el-tree
						:data="testdata"
						ref="tree"
						show-checkbox
						node-key="id"
						:props="defaultProps"
					>
					</el-tree>
				</div>
				<div>运行数据</div>
				<div style="margin-bottom: 0">
					<el-checkbox
						v-model="ShowTime[1]"
						label="时间"
						size="large"
					/>
				</div>
				<div>
					<el-checkbox-group v-model="checked1">
						<el-checkbox
							size="large"
							v-for="(item, index) in state.yunxing"
							:key="index"
							:label="item.label"
						>
							{{ item.label }}
						</el-checkbox>
					</el-checkbox-group>
				</div>
				
				<div>能耗能效</div>
				<el-checkbox label="时间" v-model="ShowTime[2]" size="large" />
				<div>
					<el-checkbox-group v-model="checked2">
						<el-checkbox
							size="large"
							v-for="(item, index) in state.nenghao"
							:key="index"
							:label="item.label"
						>
							{{ item.label }}
						</el-checkbox>
					</el-checkbox-group>
				</div>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false" class="quxiao-btn"
						>取消</el-button
					>
					<el-button type="primary" @click="saveProp" class="sava-btn"
						>保存</el-button
					>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { onMounted, reactive, ref, computed, toRaw } from "vue";
import { YunXing, Lengji } from "@/api/model/end";
import FileSaver from "file-saver";
import * as XLSX from "xlsx/dist/xlsx.mini.min.js";
import dayjs from "dayjs";
const tableStatus = ref("machineData");
let dialogVisible = ref(false);

// 树形控件的实例
let tree = ref(null);


let dialog = ref(null);
const defaultProps = {
	children: "children",
	label: "label",
};
// 控制三个时间字段的显示
let ShowTime = ref([]);
// 给table 一个key值 防止复用
const getRowKeys = (row) => {
	return row.id;
};
// const handleSizeChange = (val) => {
// 	console.log(`${val} items per page`);
// };
// const handleCurrentChange = (val) => {
// 	console.log(`current page: ${val}`);
// };
// 运行数据的选择项
const checked1 = ref([]);
// 能耗能效的选择项
const checked2 = ref([]);
// 全选和反选
const ckAll = computed({
	get() {
		//
		return (
			checked1.value.length === 6 &&
			checked2.value.length === 11 &&
			ShowTime.value.every((i) => i) &&
			tree.value.getCheckedNodes().filter((i) => i.children).length === 4
		);
	},
	set(val) {
		if (val) {
			console.log(tree.value.getCheckedNodes());
			tree.value.setCheckedNodes(testdata.value);
			checked1.value = state.yunxing.map((i) => i.label);
			checked2.value = state.nenghao.map((i) => i.label);
			ShowTime.value = [true, true, true];
		} else {
			tree.value.setCheckedKeys([], false);
			checked1.value = [];
			checked2.value = [];
			ShowTime.value = [false, false, false];
		}
	},
});

let testdata = ref([
	{
		id: "1",
		label: "冷机运行状态",
		children: [
			{
				id: "5",
				label: "1#",
				prop: "statusOne",
			},
			{
				id: "6",
				label: "2#",
				prop: "statusTwo",
			},
			{
				id: "7",
				label: "3#",
				prop: "statusThree",
			},
		],
	},
	{
		id: "2",
		label: "冷机运行功率",
		children: [
			{
				id: "8",
				label: "1#",
				prop: "ratingOne",
			},
			{
				id: "9",
				label: "2#",
				prop: "ratingTwo",
			},
			{
				id: "10",
				label: "3#",
				prop: "ratingThree",
			},
		],
	},
	{
		id: "3",
		label: "冷机冷冻水出水温度（℃）",
		children: [
			{
				id: "11",
				label: "1#",
				prop: "temperatureOne",
			},
			{
				id: "12",
				label: "2#",
				prop: "temperatureTwo",
			},
			{
				id: "13",
				label: "3#",
				prop: "temperatureThree",
			},
		],
	},
	{
		id: "4",
		label: "冷机负载（%）",
		children: [
			{
				id: "14",
				label: "1#",
				prop: "loadOne",
			},
			{
				id: "15",
				label: "2#",
				prop: "loadTwo",
			},
			{
				id: "16",
				label: "3#",
				prop: "loadThree",
			},
		],
	},
]);

const tableData = ref([
	{
		date: "2016-05-03",
		status_one: "关",
		status_two: "关",
		status_three: "关",
		power_one: "0.573",
		power_two: "0.573",
		power_three: "0.573",
		temperature_one: "21.83",
		temperature_two: "21.83",
		temperature_three: "21.83",
		load_one: "0.000",
		load_two: "0.000",
		load_three: "0.000",
	},
]);

const tableDataOperating = ref([
	{
		date: "2016-05-03",
		water: "21.86",
		backwater: "21.86",
		onewater: "21.86",
		twowater: "21.86",
		power: "21.86",
		efficiency: "21.86",
	},
]);

const tableDataQualified = ref([
	{
		date: "2016-05-03",
		energy: "0.000",
		refrigerating: "0.000",
		computerroom: "0.000",
		machineefficiency: "0.000",
		afrozen: "0.000",
		refrigeran: "0.000",
		pumpefficiency: "0.000",
		towerefficiency: "0.000",
		average_temperature: "0.000",
		minimum_temperature: "0.000",
		maximum_temperature: "0.000",
	},
]);

const state = reactive({
	yunxing: [
		{
			label: "冷冻水供水温度",
			prop: "supplyWaterTemperature",
		},
		{
			label: "冷冻水回水温度",
			prop: "returnWaterTemperature",
		},
		{
			label: "#1、#2冷却塔出塔水温",
			prop: "oneTowTemperature",
		},
		{
			label: "#3冷却塔出塔水温",
			prop: "threeTemperature",
		},
		{
			label: "冷源机房功率",
			prop: "enginePower",
		},
		{
			label: "系统实时效率",
			prop: "realTimeEfficiency",
		},
	],

	nenghao: [
		{
			label: "冷战今日能耗(kWh)",
			prop: "energy",
		},
		{
			label: "今日制冷量(tonh)",
			prop: "refrigerating",
		},
		{
			label: "今日机房效率(kW/ton)",
			prop: "computerroom",
		},
		{
			label: "今日冷机效率(kW/ton)",
			prop: "machineefficiency",
		},
		{
			label: "今日一次冷冻泵效率(kW/ton)",
			prop: "afrozen",
		},
		{
			label: "今日二次冷冻泵效率(kW/ton)",
			prop: "refrigeran",
		},
		{
			label: "今日冷却泵效率(kW/ton)",
			prop: "pumpefficiency",
		},
		{
			label: "今日冷却塔效率(kW/ton)",
			prop: "towerefficiency",
		},
		{
			label: "平均干球温度(°C)",
			prop: "average_temperature",
		},
		{
			label: "最低干球温度(°C)",
			prop: "minimum_temperature",
		},
		{
			label: "最高干球温度(°C)",
			prop: "maximum_temperature",
		},
	],
});
// 最终展示字段的数据
let midData = reactive({
	refrigerator:
		JSON.parse(localStorage.getItem("test")) || toRaw(testdata.value),
	runtime: JSON.parse(localStorage.getItem("run")) || toRaw(state.yunxing),
	energy: JSON.parse(localStorage.getItem("energy")) || toRaw(state.nenghao),
	show: JSON.parse(localStorage.getItem("showTime")) || [true, true, true],
});

// dialog 没有打开时默认不渲染 需要在打开创建的时候赋值
const open = () => {
	console.log(tree.value);
	ShowTime.value = JSON.parse(localStorage.getItem("showTime")) || [
		true,
		true,
		true,
	];

	tree.value.setCheckedNodes(midData.refrigerator);
	console.log(tree.value.getCheckedNodes());
	checked1.value = midData.runtime.map((i) => i.label);
	checked2.value = midData.energy.map((i) => i.label);
};
// 将选中的菜单 存储到本地存储中
const saveProp = () => {
	localStorage.setItem("showTime", JSON.stringify(ShowTime.value));
	localStorage.setItem(
		"energy",
		JSON.stringify(
			state.nenghao.filter((i) => {
				if (checked2.value.find((opt) => opt === i.label)) {
					return i;
				}
			})
		)
	);
	localStorage.setItem(
		"run",
		JSON.stringify(
			state.yunxing.filter((i) => {
				if (checked1.value.find((opt) => opt === i.label)) {
					return i;
				}
			})
		)
	);
	// 处理选择的节点数据
	let col = tree.value
		// 获取包括半选节点
		.getCheckedNodes(false, true)
		.filter((i) => i.children)
		.map((item) => {
			item.children = item.children.filter((leaf) => {
				if (
					// 获取所有被选择的子节点
					tree.value.getCheckedKeys(true).find((id) => id == leaf.id)
				) {
					return leaf;
				}
			});
			return item;
		});

	localStorage.setItem("test", JSON.stringify(col));
	setData();
	dialogVisible.value = false;
};
// 保存之后从本地存储中取出最新的值
const setData = () => {
	midData.refrigerator =
		JSON.parse(localStorage.getItem("test")) || toRaw(testdata.value);
	midData.runtime =
		JSON.parse(localStorage.getItem("run")) || toRaw(state.yunxing);
	midData.energy =
		JSON.parse(localStorage.getItem("energy")) || toRaw(state.nenghao);
	midData.show = JSON.parse(localStorage.getItem("showTime")) || [
		true,
		true,
		true,
		true,
	];
};

const machine_data = () => {
	tableStatus.value = "machineData";
};
function exportExcel() {
	//需给表格定义一个id或者类名
	console.log("1111111111", XLSX);
	let wb = XLSX.utils.table_to_book(document.querySelector("#table"));
	console.log("222");
	let wbout = XLSX.write(wb, {
		bookType: "xlsx",
		bookSST: true,
		type: "array",
	});
	try {
		FileSaver.saveAs(
			new Blob([wbout], { type: "application/octet-stream" }),
			"111.xlsx"
		); //***是自己导出文件时的命名，随意
	} catch (e) {
		if (typeof console !== "undefined") console.log(e, wbout);
	}
	return wbout;
}
const operating_data = () => {
	tableStatus.value = "operatingData";
};

onMounted(() => {
	getYunXings();
	getLengjis();
	// 提前渲染dialog

	dialog.value.rendered = true;

	console.log("123", tree.value);
	
});

// 获取打印报表，运行数据
const getYunXings = async () => {
	let res = await YunXing();
	if (res.code == 200) {
		tableDataOperating.value = res.data;
	}
};

// 获取打印报表，冷机数据
const getLengjis = async () => {
	let res = await Lengji();
	if (res.code == 200) {
		tableData.value = res.data;
	}
};

const qualified = () => [(tableStatus.value = "qualified")];
</script>

<style lang="less" scoped>
.box {
	display: flex;

	.card-css {
		flex: 1;
		width: 1760px;
		height: 817px;
		position: relative;

		.zhpj {
			position: absolute;
			border-bottom: 1px solid #d9deec;
			margin-right: 120px;
			margin-left: -20px;
			padding-left: 20px;
			padding-bottom: 20px;
			width: 100%;

			.zhpj-span {
				font-family: SourceHanSansSC-medium;
				font-weight: 700;
				color: #4d62a5;
				font-size: 20px;
			}
		}

		.table-css {
			display: flex;
			margin-top: 66px;
			justify-content: end;

			.select01 {
				width: 100px;
			}

			.select02 {
				width: 100px;
				margin-right: 20px;
				margin-left: 20px;
			}

			.btn-01 {
				margin-left: 20px;
				margin-right: 20px;
			}

			.el-button {
				background-color: #8faadc;
				border-color: #8faadc;
			}

			.btn-css {
				flex-grow: 1;
			}
		}
	}

	.table {
		margin-top: 20px;

		.el-checkbox {
			top: 3px;
			margin-left: 5px;
		}
	}

	.pagination {
		display: flex;
		justify-content: flex-end;
	}
}

:deep(.el-dialog__title) {
	color: #4d62a5;
}
:deep(.el-checkbox-group) {
	display: flex;
	flex-wrap: wrap;
}

.zdyDialog {
	width: 1000px;
}

.sava-btn {
	border-color: #8faadc;
	background-color: #8faadc;
}

.quxiao-btn {
	border-color: #cccccc;
	background-color: #cccccc;
	color: #fff;
}

:deep(.el-tree-node.is-expanded > .el-tree-node__children) {
	display: inline-flex;
}

.checkbox-div > div {
	margin-bottom: 10px;
}
.checkbox-div .el-checkbox {
	width: 40%;
}

:deep(.el-tree-node__content) {
	margin-bottom: 8px;
}

:deep(.el-dialog__body) {
	border-top: 1px solid #e7eaf3;
	border-bottom: 1px solid #e7eaf3;
}
</style>
